#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
int main()
{
    int pipeArr[2] = {0};
    int n = pipe(pipeArr);
    if (n < 0)
    {
        cout << "pipe error : " << strerror(errno) << endl;
    }
    pid_t id = fork();
    if (id == 0)
    {
        // child w
        close(pipeArr[0]);
        int cnt = 10;
        char wbuff[1024];
        while (cnt--)
        {
            snprintf(wbuff, sizeof wbuff, "I am child, pid:%d, cnt: %d\n", getpid(), cnt);
            write(pipeArr[1], wbuff, strlen(wbuff));
            sleep(1);
        }
        exit(1);
    }
    // father r
    close(pipeArr[1]);
    char rbuff[1024];
    ssize_t idx = 0;
    while (idx = read(pipeArr[0], rbuff, sizeof rbuff - 1))
    {
        if (idx > 0)
        {
            rbuff[idx] = '\0';
            cout << "father get a message : " << rbuff;
        }
        else if(idx == 0)
        {
            cout << "child write done...." << endl;
            break;
        }
    }
    pid_t rid = waitpid(id, NULL, 0);
    if(rid == id)
    {
        cout << "father wait child success" << endl;
    }
    else
    {
        cout << "father wait child error : " << strerror(errno) << endl;
    }

    return 0;
}